package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import Modelo.BO.UsuarioBO;

public class LoginServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
    
    public LoginServlet() 
    {
    	super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		String loginCorrente = request.getParameter("usuario");
		String senhaCorrente = request.getParameter("senha");
		RequestDispatcher rd = null;
		
		try 
		{
			if(UsuarioBO.getInstance().ValidaUsuario(loginCorrente, senhaCorrente))
			{
				HttpSession session = request.getSession();
				session.setAttribute("usuario", loginCorrente);
				
				RequestDispatcher reqDispatcher = request.getRequestDispatcher("index.jsp");
				reqDispatcher.forward(request, response);
			}
			else
				response.sendRedirect("login.jsp");
		} 
		catch (Exception e) 
		{
			rd = request.getRequestDispatcher(montaCaminhoErro(e.getMessage(), "Login", "Houve um erro ao tentar executar o Login."));
			rd.forward(request, response);
		}
	}
	
	private String montaCaminhoErro(String mensagemExcecao, String tituloPagina, String mensagemEspecifica)
	{
		return "pages/rotulo/rotuloErroGeral.jsp?tituloPagina=" + tituloPagina + "&mensagem=" + mensagemEspecifica + " Exception: " + mensagemExcecao;
	}
}
